
import { resolve } from 'path';
import { MongoClient } from 'mongodb';
import { rules } from '../../../utils/rules';
import { readFileSync, writeFileSync } from 'fs'
const installPath = resolve(__dirname, '../../../config/install.json');
const install = readFileSync(installPath, { encoding: 'utf-8' });
const list = {
  username: { type: String, required: true },
  password: { type: String, required: true },
  dbhost: { type: String, required: true },
  dbname: { type: String, required: true },
  dbport: { type: Number, required: true },
  dbuser: { type: String, required: true },
  dbpass: { type: String, required: true },
}
export default class Install {
  async list(req: any, res: any) {
    let obj = JSON.parse(install);
    res.send({ data: obj, code: 200 });
  }
  async install(req: any, res: any) {
    try {
      let { data, error, message } = rules(req.body, list);
      if (error) throw message;
      let { username, password, dbhost, dbname, dbport, dbuser, dbpass } = data;
      MongoClient.connect(`mongodb://${dbuser}:${dbpass}@${dbhost}:${dbport}`, { useUnifiedTopology: true, }, async (e, db: any) => {
        if (e) throw e;
        const coll = db.db(dbname).collection('user');
        const { reslut } = await coll.insertOne({ id: 1, username, password, roles: [], superAdmin: true });
        res.send({ code: 200, message: '安装完成' });
        writeFileSync(installPath, JSON.stringify({ ...data, install: true }, null, 4));
      });
    } catch (error) {
      res.send({ code: 400, message: '安装失败', data: error })
    }
  }
}